#include "settingsdialog.h"
#include "ui_settingsdialog.h"
#include <QDir>
#include <QLocale>

SettingsDialog::SettingsDialog(SystemController *controller, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);
    this->systemController = controller;

    //Fill the ComboBox for Language
    QString translationPath = QApplication::applicationDirPath();
    translationPath.append("/translation");
    QDir dir(translationPath);
    QStringList fileNames = dir.entryList(QStringList("trainermanagement_*.qm"));

    for (int i = 0; i < fileNames.size(); ++i)
    {
        // get locale extracted by filename
        QString locale;
        locale = fileNames[i];
        locale.truncate(locale.lastIndexOf('.'));
        locale.remove(0, locale.indexOf('_') + 1);

        QString lang = QLocale::languageToString(QLocale(locale).language());
        ui->comboBox->addItem(lang, locale);
    }

    ui->comboBox->addItem(QLocale::languageToString(QLocale::English), "en");

    //Set the current Language
    for (int i=0; i < ui->comboBox->count(); i++)
    {
        QLocale lc(this->systemController->getLanguage());
        if (ui->comboBox->itemText(i) == QLocale::languageToString(lc.language()))
            ui->comboBox->setCurrentIndex(i);
    }
}

SettingsDialog::~SettingsDialog()
{
    delete ui;
}

/*!
  \fn accept
  Function called when Dialog is accepted
  */
void SettingsDialog::accept()
{
    QMessageBox::information(this, tr("Please restart Application"), tr("Please restart the application to apply the changes"));
    QDialog::accept();
}


/////////////////////
//Getter functions//
///////////////////
QString SettingsDialog::getLanguage()
{
    QString selection = ui->comboBox->itemData(ui->comboBox->currentIndex()).toString();
    QLocale locale(selection);
    QString name = locale.name();
    name.truncate(name.lastIndexOf('_'));
    return name;
}
